package com.qingzhuge.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : zero.xiao
 * @description : 日期操作辅助类
 * @modified :
 */
public final class DateUtil {
    private static final Map<String, DateTimeFormatter> DATE_TIME_FORMATTER_MAP = new ConcurrentHashMap<>();
    private DateUtil() {
    }

    /**
     * 日期格式
     **/
    public interface DATE_PATTERN {
        String HHMMSS = "HHmmss";
        String HH_MM_SS = "HH:mm:ss";
        String YYYYMMDD = "yyyyMMdd";
        String YYYY_MM_DD = "yyyy-MM-dd";
        String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
        String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";
        String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
        String YYYY_MM_DD_HH_MM_SS_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
    }

    public static DateTimeFormatter getFormat(String pattern){
        if (!DATE_TIME_FORMATTER_MAP.containsKey(pattern)) {
            DATE_TIME_FORMATTER_MAP.put(pattern, DateTimeFormatter.ofPattern(pattern));
        }
        return DATE_TIME_FORMATTER_MAP.get(pattern);
    }

    public static String format(Date date) {
        return format(date, DATE_PATTERN.YYYY_MM_DD);
    }

    public static String format(Date date, String pattern) {
        if (date != null) {
            if (pattern == null) {
                return format(date);
            }else {
                return getFormat(pattern).format(TimeUtil.date2LocalDateTime(date));
            }
        }
        return null;
    }

    /**
     * 格式化日期
     * yyyy-MM-dd
     */
    public static String format(Long date) {
        return format(date, DATE_PATTERN.YYYY_MM_DD);
    }

    /**
     * 格式化日期
     */
    public static String format(Long date, String pattern) {
        if (date != null) {
            if (pattern == null) {
                return format(date);
            }else {
                return getFormat(pattern).format(TimeUtil.date2LocalDateTime(date));
            }
        }
        return null;
    }

    /**
     * 获取日期
     * yyyy-MM-dd
     */
    public static String getDate() {
        return format(new Date());
    }

    /**
     * 获取日期时间
     * yyyy-MM-dd HH:mm:ss
     */
    public static String getDateTime() {
        return format(new Date(), DATE_PATTERN.YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 获取日期
     */
    public static String getDateTime(String pattern) {
        return format(new Date(), pattern);
    }

    /**
     * 日期计算
     */
    public static Date addDate(Date date, int field, int amount) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(field, amount);
        return calendar.getTime();
    }

    /**
     * 字符串转换为日期:不支持yyM[M]d[d]格式
     */
    public static Date stringToDate(String date) {
        if (date == null) {
            return null;
        }
        String separator = String.valueOf(date.charAt(4));
        String pattern = "yyyyMMdd";
        if (!separator.matches("\\d*")) {
            pattern = "yyyy" + separator + "MM" + separator + "dd";
            if (date.length() < 10) {
                pattern = "yyyy" + separator + "M" + separator + "d";
            }
            pattern += " HH:mm:ss.SSS";
        } else if (date.length() < 8) {
            pattern = "yyyyMd";
        } else {
            pattern += "HHmmss.SSS";
        }
        pattern = pattern.substring(0, Math.min(pattern.length(), date.length()));
        try {
            return new SimpleDateFormat(pattern).parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 间隔天数
     */
    public static Integer getDayBetween(Date startDate, Date endDate) {
        Calendar start = setCalendar(startDate);
        Calendar end = setCalendar(endDate);
        long n = end.getTimeInMillis() - start.getTimeInMillis();
        return (int) (n / (60 * 60 * 24 * 1000L));
    }

    private static Calendar setCalendar(Date startDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar;
    }

    /**
     * 间隔月
     */
    public static Integer getMonthBetween(Date startDate, Date endDate) {
        if (startDate == null || endDate == null || !startDate.before(endDate)) {
            return null;
        }
        Calendar start = Calendar.getInstance();
        start.setTime(startDate);
        Calendar end = Calendar.getInstance();
        end.setTime(endDate);
        int year1 = start.get(Calendar.YEAR);
        int year2 = end.get(Calendar.YEAR);
        int month1 = start.get(Calendar.MONTH);
        int month2 = end.get(Calendar.MONTH);
        int n = (year2 - year1) * 12;
        n = n + month2 - month1;
        return n;
    }

    /**
     * 间隔月，多一天就多算一个月
     */
    public static Integer getMonthBetweenWithDay(Date startDate, Date endDate) {
        Integer monthBetween = getMonthBetween(startDate, endDate);
        if (null == monthBetween) {
            return null;
        }
        Calendar start = Calendar.getInstance();
        start.setTime(startDate);
        Calendar end = Calendar.getInstance();
        end.setTime(endDate);
        int day1 = start.get(Calendar.DAY_OF_MONTH);
        int day2 = end.get(Calendar.DAY_OF_MONTH);
        if (day1 <= day2) {
            monthBetween++;
        }
        return monthBetween;
    }

    /**
     * 将UTC时间转换为东八区时间
     *
     * @param date 时间
     * @return 转换为东八区时间
     */
    public static String getLocalTimeFromUTC(Date date, String pattern) {
        if (StringUtils.isBlank(pattern)) {
            pattern = DATE_PATTERN.YYYY_MM_DD_HH_MM_SS;
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        return format.format(date);
    }
    /**获取当前日期的这一周日期*/
    public static List<LocalDate> dateToWeek(LocalDate date) {
        LocalDate localDate = date.with(DayOfWeek.MONDAY);
        List<LocalDate> list = new ArrayList<>();
        list.add(localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue()));
        list.add(localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.TUESDAY.getValue()));
        list.add(localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.WEDNESDAY.getValue()));
        list.add(localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.THURSDAY.getValue()));
        list.add(localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.FRIDAY.getValue()));
        list.add(localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.SATURDAY.getValue()));
        list.add(localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.SUNDAY.getValue()));
        return list;
    }

    /**
     * java8(经测试别的版本获取2月有bug) 获取某月第一天的00:00:00
     * @return LocalDateTime
     */
    public static LocalDateTime getFirstDayOfMonth(String datestr){
        LocalDateTime dateTime = getLocalDateTime(datestr, TemporalAdjusters.firstDayOfMonth());
        return dateTime.with(LocalTime.MIN);
    }
    /**
     * java8(别的版本获取2月有bug) 获取某月最后一天的23:59:59
     * @return LocalDateTime
     */
    public static LocalDateTime getLastDayOfMonth(String datestr){
        LocalDateTime dateTime = getLocalDateTime(datestr, TemporalAdjusters.lastDayOfMonth());
        return dateTime.with(LocalTime.MAX);
    }

    private static LocalDateTime getLocalDateTime(String datestr, TemporalAdjuster temporalAdjuster) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_PATTERN.YYYY_MM_DD_HH_MM_SS);
        LocalDateTime dateTime = LocalDateTime.parse(datestr, dateTimeFormatter);
        return dateTime.with(temporalAdjuster);
    }
}
